import { defineStore } from 'pinia'
import { login } from '@/api/system'
import { addUserRouter } from '@/utils'

interface IUserData {
  info: any
  token: string
  menu: any[]
}

export default defineStore('userStorage', {
  state: (): IUserData => {
    return {
      info: null,
      token: '',
      menu: []
    }
  },

  getters: {
    getUserMenu: (state) => state.menu
  },

  actions: {
    async login(params: any) {
      const result = await login(params)

      if (result?.success) {
        this.$state.token = result?.data?.token
        this.$state.info = result?.data?.userInfoDto
        this.$state.menu = result?.data?.sysMenus
        addUserRouter(result?.data?.sysMenus)
      }

      return result
    }
  },

  persist: {
    storage: sessionStorage
  }
})
